package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //新增菜品/套餐分类
    @PostMapping
    public R<String> addCategory(@RequestBody Category category) {
        log.info("接收category:{}", category);
        categoryService.save(category);
        return R.success("保存菜品分类成功");
    }

    //菜品/套餐分类界面分页查询
    @GetMapping("/page")
    public R<Page<Category>> pageCategory(int page, int pageSize) {
        log.info("接收page:{}===pageSize:{}", page, pageSize);
        //构建分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //构建条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getSort);//按照sort字段排序
        qw.orderByDesc(Category::getType);
        categoryService.page(pageInfo, qw);
        return R.success(pageInfo);
    }

    //修改菜品/套餐分类
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category) {
        log.info("接收category:{}", category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //删除菜品/套餐分类
    @DeleteMapping
    public R<String> deleteCategory(Long id) {
        log.info("接收Id:{}", id);
        //categoryService.removeById(id);
        return categoryService.removeSelf(id);

    }

    //添加菜品界面菜品分类选项
    @GetMapping("/list")
    public R<List<Category>> listCategory(Integer type) {
        //条件查询,type,判断type是否为空
        if (type == null) {
            //type为null,查询所有
            return R.success(categoryService.list());

        }
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType, type);
        List<Category> list = categoryService.list(qw);
        if (list.isEmpty()) {
            return R.fail("没有菜品分类");
        }
        return R.success(list);
    }
}
